<template>
    <div>
        <a-modal width="1200px" :visible="visible" :title="null" @cancel="closeModal" class="large-modal right3Child-modal"
            :getContainer="getParent" :footer="null" :dialog-style="{ top: '0' }">
            <a-spin tip="Loading..." :spinning="loading">
                <div style="position:relative">
                    <div class="child-title">
                        <span class="child-title-words">营销分析</span>
                    </div>
                    <div class="child-type">
                        <div class="type-list" :class="pageType==='通用券'&&'type-active'" @click="typeChage('通用券')">通用券</div>
                        <div class="type-list" :class="pageType==='商城券'&&'type-active'" @click="typeChage('商城券')">商城券</div>
                        <div class="type-list" :class="pageType==='专属券'&&'type-active'" @click="typeChage('专属券')">专属券</div>
                    </div>

                    <div class="page-content">
                        <div class="content-left">
                            <div style="padding:0 10px">
                                <a-input-search class="large-search" allowClear v-model="keywords" placeholder="活动名称"
                                    @search="searchCouponList" />
                            </div>

                            <div style="margin-top:10px;overflow:auto;height:calc(100vh - 300px)">
                                <div class="patient-list" :class="selCoupon.id===item.id &&'patient-list-s'"
                                    v-for="(item,i) in couponList" @click="clickSelCoupon(item)">
                                    <span>{{item.name}}</span>
                                </div>

                            </div>
                        </div>
                        <div class="content-right" v-if="selCouponData.basicInfo">
                            <div class="content-info">
                                <div class="log-top">
                                    <div>
                                        <div class="content-list">
                                            <span class="content-list-title">参与机构：</span>
                                            <span class="content-list-info">
                                                <span v-for="item in selCouponData.storeDetails">{{item.storeName}}，</span>
                                            </span>
                                        </div>
                                        <div class="content-list">
                                            <span class="content-list-title">发放方式：</span>
                                            <span class="content-list-info">{{selCouponData.basicInfo.issueType}}</span>
                                        </div>
                                        <div class="content-list">
                                            <span class="content-list-title">发放数量：</span>
                                            <span
                                                class="content-list-info">{{selCouponData.statistics.receivedQuantity}}/{{selCouponData.statistics.issueQuantity}}</span>
                                        </div>
                                        <div class="content-list">
                                            <span class="content-list-title">累计满减金额：</span>
                                            <span class="content-list-info">
                                                {{$toDecimalNoZero(selCouponData.statistics.usedQuantity*selCouponData.basicInfo.totalDiscountAmount)}}
                                                元
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <div class="left-box">
                                        <div style="position:relative;margin:10px 0">
                                            <img class="center-bg-img" src="@/assets/large/right3-left.png" />
                                            <div id="right3childChart1"></div>
                                        </div>
                                        <div>
                                            <div class="leg-list">
                                                <span class="leg-lab-total"></span>
                                                <span>发放数量</span>
                                                <span class="leg-num"
                                                    style="color:rgba(58, 211, 193, 1)">{{selCouponData.statistics.issueQuantity}}</span>
                                            </div>
                                            <div class="leg-list">
                                                <span class="leg-lab"
                                                    :style="`background: linear-gradient(90deg, ${color1[0]}, 1) 0%, ${color1[0]}, 0.1) 100%)`"></span>
                                                <span>已领取</span>
                                                <span class="leg-num"
                                                    :style="'color:'+color1[0]+',1)'">{{selCouponData.statistics.receivedQuantity}}</span>
                                            </div>
                                            <div class="leg-list">
                                                <span class="leg-lab"
                                                    :style="`background: linear-gradient(90deg, ${color1[1]}, 1) 0%, ${color1[1]}, 0.1) 100%)`"></span>
                                                <span>未领取</span>
                                                <span class="leg-num" :style="'color:'+color1[1]+',1)'">
                                                    {{selCouponData.statistics.issueQuantity-selCouponData.statistics.receivedQuantity}}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="right-box">
                                        <div style="position:relative;margin:10px 0">
                                            <img class="center-bg-img" src="@/assets/large/right3-right.png" />
                                            <div id="right3childChart2"></div>
                                        </div>
                                        <div>
                                            <div class="leg-list">
                                                <span class="leg-lab"
                                                    :style="`background: linear-gradient(90deg, ${color2[0]}, 1) 0%, ${color2[0]}, 0.1) 100%)`"></span>
                                                <span>已使用</span>
                                                <span class="leg-num"
                                                    :style="'color:'+color2[0]+',1)'">{{selCouponData.statistics.usedQuantity}}</span>
                                            </div>
                                            <div class="leg-list">
                                                <span class="leg-lab"
                                                    :style="`background: linear-gradient(90deg, ${color2[1]}, 1) 0%, ${color2[1]}, 0.1) 100%)`"></span>
                                                <span>未使用</span>
                                                <span class="leg-num"
                                                    :style="'color:'+color2[1]+',1)'">{{selCouponData.statistics.unusedQuantity}}</span>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                            <div class="content-table">
                                <template v-if="selCouponData.basicInfo.issueType==='用户主动领取'">
                                    <div class="child-content-title" style="margin-bottom:10px">
                                        <img class="child-content-titleico" src="@/assets/large/panel-title-ico.png" />
                                        领取详情（客户主动领取）
                                    </div>
                                    <div class="table-box large-table">
                                        <a-table bordered :rowKey="(item,i)=>'doctor_'+i" :columns="columns"
                                            :data-source="pageList" :pagination="pagination"
                                            :rowClassName="(record, index) => index % 2 === 0 ? 'even-row' : 'odd-row'">

                                        </a-table>
                                    </div>
                                </template>

                                <template v-else>
                                    <div class="child-content-title" style="margin-bottom:10px">
                                        <img class="child-content-titleico" src="@/assets/large/panel-title-ico.png" />
                                        领取详情（系统自动发放）
                                    </div>
                                    <div class="table-box large-table">
                                        <a-table bordered :rowKey="(item,i)=>'doctor_'+i" :columns="columns"
                                            :data-source="pageList" :pagination="pagination"
                                            :rowClassName="(record, index) => index % 2 === 0 ? 'even-row' : 'odd-row'">

                                        </a-table>
                                    </div>
                                </template>

                            </div>
                        </div>
                    </div>
                </div>
            </a-spin>
            <template slot="footer">
                <div></div>
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import largeApi from "@/api/largeApi";
import { format } from "@/utils";
import { Component, Prop, Watch, Vue } from "vue-property-decorator";

@Component({
    name: "tpl",
    components: {},
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    loading = false;
    pageType = "通用券";
    keywords = "";
    getParent() {
        return document.getElementById("largePage");
    }
    typeChage(type) {
        this.pageType = type;
        this.getPageData();
    }

    async mounted() {
        await this.getPageData();
        this.$nextTick(() => {
            this.setChart();
        });
    }
    selCoupon: any = {};
    couponList: any[] = [];
    couponListAll: any[] = [];
    async getPageData() {
        this.loading = true;
        try {
            const res = await largeApi.findCouponsByTypeAndOrganization({
                couponType: this.pageType,
                type:"ORGAN"
            });
            this.couponList = res.data.records;
            this.couponListAll = JSON.parse(JSON.stringify(res.data.records));
            this.selCoupon = this.couponList[0] || {};
            await this.getSelCouponData();
        } finally {
            this.loading = false;
        }
    }
    selCouponData: any = {};
    async getSelCouponData() {
        if (!this.selCoupon || !this.selCoupon.id) {
            this.selCouponData = {};
            return;
        }
        this.loading = true;
        const res = await largeApi.getCouponBigScreenDetails({
            couponId: this.selCoupon.id,
        });
        this.selCouponData = res.data;

        this.dataList1 = [
            { name: "已领取", val: this.selCouponData.statistics.receivedQuantity },
            { name: "未领取", val: this.selCouponData.statistics.issueQuantity - this.selCouponData.statistics.receivedQuantity },
        ];
        this.dataList2 = [
            { name: "已使用", val: this.selCouponData.statistics.usedQuantity },
            { name: "未使用", val: this.selCouponData.statistics.unusedQuantity },
        ];

        this.columns = [...this.columnsTpl];
        if (res.data.basicInfo.issueType === "用户主动领取") {
            this.columns.push({
                align: "center",
                dataIndex: "receiveTime",
                key: "receiveTime",
                title: "领取时间",
                customRender: (text: string, record: any, index: number) => {
                    return format(record.receiveTime);
                },
            });
        }
        await this.getPageList();
        this.loading = false;
    }

    clickSelCoupon(item) {
        this.selCoupon = item;
        this.getSelCouponData();
    }
    closeModal() {
        this.$emit("closeModal");
    }
    dataList1: any[] = [];
    dataList2: any[] = [];
    chart1: any = null;
    chart2: any = null;
    setAngleArr(list) {
        let totalValue = list.reduce((total, item) => total + item.val, 0);
        let cacheNum = 0;
        const newArr: any[] = [];
        list.forEach((item) => {
            item.numArr = [cacheNum, cacheNum + item.val];
            item.angleArr = [(cacheNum / totalValue) * Math.PI * 2, ((cacheNum + item.val) / totalValue) * Math.PI * 2];
            cacheNum += item.val;
            newArr.push(item);
        });
        return newArr;
    }
    setChart() {
        if (this.chart1) {
            this.resetChart();
        } else {
            this.initChart();
        }
    }
    resetChart() {
        const options = this.chart1.getOption();
        options.series = this.getSeries1();
        this.chart1.setOption(options, true);
    }
    initChart() {
        const chartDom1 = document.getElementById("right3childChart1");
        const chartDom2 = document.getElementById("right3childChart2");
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        const options1: any = {
            legend: {
                show: false,
            },
            tooltip: {
                trigger: "item",
            },
            series: this.getSeries1(),
        };
        const options2: any = {
            legend: {
                show: false,
            },
            tooltip: {
                trigger: "item",
            },
            series: this.getSeries2(),
        };
        if (chartDom1) {
            this.chart1 = window.echarts.init(chartDom1 as HTMLDivElement);
            this.chart1.setOption(options1);
        }
        if (chartDom2) {
            this.chart2 = window.echarts.init(chartDom2 as HTMLDivElement);
            this.chart2.setOption(options2);
        }
    }
    color1 = ["rgba(235,108,72", "rgba(50,139,201"];
    color2 = ["rgba(9,204,165", "rgba(117,178,221"];
    getSeries1() {
        return [
            {
                name: "",
                type: "pie",
                radius: ["64%", "84%"],
                center: ["50%", "50%"],
                avoidLabelOverlap: false,
                padAngle: 2,
                itemStyle: {
                    borderRadius: 2,
                },
                label: {
                    show: false,
                    position: "center",
                },

                labelLine: {
                    show: false,
                },
                data: this.dataList1.map((item, idx) => {
                    return {
                        value: item.val,
                        name: item.name,
                        itemStyle: {
                            color: this.color1[idx] + ",1)",
                        },
                    };
                }),

                // this.dataList1.map((item, idx) => {
                //     return {
                //         value: item.val,
                //         name: item.name,
                //         itemStyle: {
                //             color: {
                //                 ...this.getCoordinates(item.angleArr[0], item.angleArr[1]),
                //                 type: "linear",
                //                 colorStops: [
                //                     {
                //                         offset: 0,
                //                         color: this.color1[idx] + ",0.1)", // 0%处的颜色
                //                     },
                //                     {
                //                         offset: 1,
                //                         color: this.color1[idx] + ",1)", // 100%处的颜色
                //                     },
                //                 ],
                //             },
                //         },
                //     };
                // }),
            },
        ];
    }
    getSeries2() {
        return [
            {
                name: "",
                type: "pie",
                radius: ["64%", "84%"],
                center: ["50%", "50%"],
                avoidLabelOverlap: false,
                padAngle: 2,
                itemStyle: {
                    borderRadius: 2,
                },
                label: {
                    show: false,
                    position: "center",
                },

                labelLine: {
                    show: false,
                },
                data: this.dataList2.map((item, idx) => {
                    return {
                        value: item.val,
                        name: item.name,
                        itemStyle: {
                            color: this.color2[idx] + ",1)",
                        },
                    };
                    // return {
                    //     value: item.val,
                    //     name: item.name,
                    //     itemStyle: {
                    //         color: {
                    //             ...this.getCoordinates(item.angleArr[0], item.angleArr[1]),
                    //             type: "linear",
                    //             colorStops: [
                    //                 {
                    //                     offset: 0,
                    //                     color: this.color2[idx] + ",0.1)", // 0%处的颜色
                    //                 },
                    //                 {
                    //                     offset: 1,
                    //                     color: this.color2[idx] + ",1)", // 100%处的颜色
                    //                 },
                    //             ],
                    //         },
                    //     },
                    // };
                }),
            },
        ];
    }

    getCoordinates(startArc: number, endArc: number) {
        const posi = [Math.sin(startArc), -Math.cos(startArc), Math.sin(endArc), -Math.cos(endArc)];
        const dx = posi[2] - posi[0];
        const dy = posi[3] - posi[1];
        return this.getLocation(dx, dy);
    }
    getLocation(dx: number, dy: number) {
        const tanv = dx / dy;
        const directSign = Math.abs(tanv) < 1;
        const t = directSign ? tanv : 1 / tanv;
        const sign1 = t > 0 ? 1 : -1;
        const sign2 = dx > 0 ? 1 : -1;
        const sign = directSign ? sign1 * sign2 : sign2;
        const group1 = [0.5 - (sign * t) / 2, 0.5 + (sign * t) / 2];
        const group2 = sign > 0 ? [0, 1] : [1, 0];
        const group = [...group1, ...group2];
        const keys = directSign ? ["x", "x2", "y", "y2"] : ["y", "y2", "x", "X2"];
        let res: any = {};
        keys.forEach((k, idx) => {
            res[k] = group[idx];
        });
        return res;
    }

    pagination = {
        current: 1,
        pageSize: 10,
        total: 1,
        onChange: this.pageChange,
    };
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getPageList();
    }
    async getPageList() {
        this.loading = true;
        const res = await largeApi.getCouponReceiveDetails({
            pageNum: this.pagination.current,
            pageSize: this.pagination.pageSize,
            couponId: this.selCoupon.id,
        });
        this.pageList = res.data.records;
        this.pagination.total = res.data.total;
        this.loading = false;
    }
    pageList: any[] = [
        { name: "2025/09/01", type: "挂号费", doctor: "10", depart: "微信" },
        { name: "2025/09/01", type: "甘草片", doctor: "20", depart: "现金" },
        { name: "2025/09/01", type: "推拿治疗", doctor: "50", depart: "微信" },
        { name: "2025/09/01", type: "收费", doctor: "70", depart: "现金" },
        { name: "2025/09/01", type: "收费", doctor: "452", depart: "微信" },
    ];
    columns: any[] = [];
    columnsTpl = [
        {
            align: "center",
            dataIndex: "userName",
            key: "userName",
            title: "用户名称",
        },
        {
            align: "center",
            dataIndex: "userPhone",
            key: "userPhone",
            title: "用户账号",
        },
        {
            align: "center",
            dataIndex: "useStatus",
            key: "useStatus",
            title: "使用状态",
        },
        {
            align: "center",
            dataIndex: "useTime",
            key: "useTime",
            title: "使用时间",
            customRender: (text: string, record: any, index: number) => {
                return format(record.useTime);
            },
        },
    ];

    searchCouponList() {
        if (this.keywords) {
            this.couponList = this.couponListAll.filter((item) => {
                let str = item.name;
                return str.indexOf(this.keywords) >= 0;
            });
        } else {
            this.couponList = JSON.parse(JSON.stringify(this.couponListAll));
        }
        this.selCoupon = this.couponList[0] || {};
        this.getSelCouponData();
    }
}
</script>
<style lang="scss">
.right3Child-modal {
    #right3childChart1 {
        width: 100%;
        height: 12vh;
    }
    #right3childChart2 {
        width: 100%;
        height: 12vh;
    }
    .ant-modal-body {
        max-height: calc(100vh - 50px);
    }
    .child-type {
        padding: 15px 0;
    }
    .type-list {
        width: 120px;
        height: 40px;
        background-size: 100%;
        background-image: url("@/assets/large/type.png");
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        cursor: pointer;
        margin-right: 15px;
    }
    .type-active {
        background-image: url("@/assets/large/type-s.png");
    }

    .page-content {
        display: flex;
        border: solid 1px rgba(58, 211, 193, 0.5);
        border-radius: 4px;
        margin-top: 15px;
        display: flex;
    }
    .content-left {
        display: inline-block;
        width: 20%;
        max-width: 200px;
        border-right: solid 1px rgba(58, 211, 193, 0.5);
        padding: 10px 0;
        flex-shrink: 0;
    }

    .content-right {
        flex-grow: 1;
        padding: 15px;
        display: flex;
    }
    .patient-list {
        font-size: 14px;
        padding: 10px;
        color: #fff;
        border-top: solid 1px rgba(58, 211, 193, 0.2);
        cursor: pointer;
    }
    .patient-list:hover {
        background-color: rgba(58, 211, 193, 0.2);
    }
    .patient-list-s {
        background-color: rgba(58, 211, 193, 0.4);
    }

    .content-box {
        padding: 10px 0;
        padding-left: 25px;
    }
    .content-list {
        padding: 2px;
        display: flex;
    }
    .content-list-title {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.8);
        vertical-align: top;
        display: inline-block;
        flex-shrink: 0;
    }
    .content-list-info {
        font-size: 14px;
        color: rgba(255, 255, 255, 1);
        display: inline-block;
        vertical-align: top;
    }

    .log-top {
        display: flex;
        align-items: center;
    }

    .left-box {
        width: 50%;
        position: relative;
        display: inline-block;
    }
    .center-bg-img {
        width: 65%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }

    .right-box {
        width: 50%;
        position: relative;
        display: inline-block;
        vertical-align: top;
    }

    .leg-list {
        color: #fff;
        font-size: 12px;
        background: linear-gradient(90deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.04) 100%);
        border-radius: 4px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        padding: 1px 10px;
        margin: 0 auto;
        margin-bottom: 4px;
        width: 16vh;
    }
    .leg-list:last-child {
        margin-bottom: 0;
    }
    .leg-num {
        font-size: 18px;
        font-weight: bold;
        margin-left: 10px;
    }
    .leg-lab {
        width: 20px;
        height: 10px;
        display: inline-block;
        margin-right: 5px;
        border-radius: 2px;
    }
    .leg-lab-total {
        height: 10px;
        width: 10px;
        background-color: rgba(58, 211, 193, 1);
        border-radius: 10px;
        display: inline-block;
        margin: 0 5px;
    }
    .data-select-parent {
        padding-left: 30px;
    }

    .content-info {
        width: 350px;
    }
    .content-table {
        flex-grow: 1;
    }
}
</style>
